<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="800px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="formRules">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="是否启用" prop="isActive">
                    <el-select v-model="formData.isActive" placeholder="请选择是否启用" class="w-full">
                        <el-option label="启用" :value="1" />
                        <el-option label="禁用" :value="0" />
                    </el-select>
                </el-form-item>
                
                <el-form-item label="菜单ID" prop="menuId">
                    <el-input v-model="formData.menuId" placeholder="请输入菜单ID" />
                </el-form-item>
                
                <!-- 文本内容 - 动态列表 -->
                <el-form-item label="文本内容" prop="textList">
                    <div class="w-full">
                        <div v-for="(text, index) in formData.textList" :key="index" class="flex items-center mb-2">
                            <el-input 
                                v-model="formData.textList[index]" 
                                type="textarea"
                                :rows="3"
                                placeholder="请输入文本内容"
                                class="flex-1 mr-2"
                            />
                            <el-button 
                                type="primary" 
                                size="small" 
                                @click="addTextItem"
                                class="mr-2"
                            >
                                新增
                            </el-button>
                            <el-button 
                                type="danger" 
                                size="small" 
                                @click="removeTextItem(index)"
                                :disabled="formData.textList.length <= 1"
                            >
                                删除
                            </el-button>
                        </div>
                    </div>
                </el-form-item>

                <!-- 图片列表 -->
                <el-form-item label="图片内容" prop="imageList">
                    <div class="w-full">
                        <div v-for="(image, index) in formData.imageList" :key="index" class="flex items-center mb-2">
                            <div class="flex-1 mr-2">
                                <el-upload
                                    class="upload-demo"
                                    :show-file-list="false"
                                    :before-upload="(file) => beforeImageUpload(file, index)"
                                    accept="image/*"
                                >
                                    <el-button size="small" type="primary">选择图片</el-button>
                                </el-upload>
                                <div v-if="image" class="mt-2">
                                    <el-image 
                                        :src="image" 
                                        style="width: 100px; height: 100px" 
                                        fit="cover"
                                        :preview-src-list="[image]"
                                    />
                                    <div class="text-xs text-gray-500 mt-1">{{ image }}</div>
                                </div>
                            </div>
                            <el-button 
                                type="danger" 
                                size="small" 
                                @click="removeImageItem(index)"
                            >
                                删除
                            </el-button>
                        </div>
                        <el-button type="primary" size="small" @click="addImageItem">添加图片</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </popup>
    </div>
</template>
<script lang="ts" setup name="sectionsEdit">
import type { FormInstance } from 'element-plus'
import { sectionsEdit, sectionsAdd, sectionsGetAllSub,sectionsGetContent } from '@/api/sections'
import { uploadImg } from '@/api/uploads'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑内容板块' : '新增内容板块'
})

const formData = reactive({
        id: '',
        name: '',
        isActive: 1,
        menuId: '', // 父级ID字段
        textList: [''],
        imageList: ['']
    })

const formRules = {
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ],
    isActive: [
        {
            required: true,
            message: '请选择是否启用',
            trigger: ['change']
        }
    ],
    textList: [
        {
            validator: (rule: any, value: string[], callback: any) => {
                const validTexts = value.filter(text => text && text.trim() !== '')
                if (validTexts.length === 0) {
                    callback(new Error('至少需要一个有效的文本内容'))
                } else {
                    callback()
                }
            },
            trigger: ['blur', 'change']
        }
    ],
    imageList: [
        {
            validator: (rule: any, value: string[], callback: any) => {
                // 图片列表可以为空，但如果有值则不能为空字符串
                const hasInvalidImage = value.some(img => img !== '' && !img)
                if (hasInvalidImage) {
                    callback(new Error('图片URL不能为空'))
                } else {
                    callback()
                }
            },
            trigger: ['blur', 'change']
        }
    ]
}

// 文本列表操作
const addTextItem = () => {
    formData.textList.push('')
}

const removeTextItem = (index: number) => {
    if (formData.textList.length > 1) {
        formData.textList.splice(index, 1)
    }
}

// 图片列表操作
const addImageItem = () => {
    formData.imageList.push('')
}

const removeImageItem = (index: number) => {
    formData.imageList.splice(index, 1)
}

// 图片上传前的处理
const beforeImageUpload = async (file: File, index: number) => {
    // 验证文件类型
    const isImage = file.type.startsWith('image/')
    if (!isImage) {
        feedback.msgError('只能上传图片文件！')
        return false
    }

    // 验证文件大小（限制为5MB）
    const isLt5M = file.size / 1024 / 1024 < 5
    if (!isLt5M) {
        feedback.msgError('图片大小不能超过5MB！')
        return false
    }

    try {
        // 创建FormData对象
        const uploadFormData = new FormData()
        uploadFormData.append('file', file)

        // 调用上传API
        const response = await uploadImg(uploadFormData)
        
        // 处理响应格式：{ code: 1, msg: null, data: { objectName: "...", url: "..." }, ok: true }
        let imageUrl = ''
        if (response && typeof response === 'object') {
            // 检查标准返回格式
            if (response.data && response.data.url) {
                imageUrl = response.data.url.trim() // 去除可能的空格
            } 
            // 兼容其他可能的格式
            else if (response.url) {
                imageUrl = response.url
            } else if (response.data && typeof response.data === 'string') {
                imageUrl = response.data
            }
        } else if (typeof response === 'string') {
            imageUrl = response
        }

        if (imageUrl) {
            // 保存图片URL到对应的索引位置
            formData.imageList[index] = imageUrl
            feedback.msgSuccess('图片上传成功')
        } else {
            feedback.msgError('图片上传失败：无法获取图片URL')
        }
    } catch (error) {
        console.error('图片上传失败:', error)
        feedback.msgError('图片上传失败，请重试')
    }

    // 阻止默认上传行为
    return false
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    
    // 过滤空的文本和图片
    const data: any = { 
        ...formData,
        textList: formData.textList.filter(text => text && text.trim() !== ''),
        imageList: formData.imageList.filter(img => img && img.trim() !== '')
        // 使用formData中的menuId值
    }
    
    // 新增时不传递id字段，编辑时保留id字段
    if (mode.value === 'add') {
        delete data.id
    }
    
    // 编辑模式时确保ID存在
    else if (mode.value === 'edit' && !data.id) {
        console.error('编辑模式下ID不能为空')
        feedback.msgError('编辑数据异常，请重新打开编辑窗口')
        return
    }
    
    console.log('提交数据:', { mode: mode.value, data })
    
    mode.value == 'edit' ? await sectionsEdit(data) : await sectionsAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const resetFormData = () => {
    formData.id = ''
    formData.name = ''
    formData.isActive = 1
    formData.textList = ['']
    formData.imageList = ['']
}

const open = (type = 'add') => {
    mode.value = type
    if (type === 'add') {
        resetFormData()
    }
    popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            if (key === 'textList' || key === 'imageList') {
                // 确保数组字段正确处理
                //@ts-ignore
                formData[key] = Array.isArray(data[key]) ? [...data[key]] : [data[key] || '']
            } else {
                //@ts-ignore
                formData[key] = data[key]
            }
        }
    }
    
    // 确保textList和imageList至少有一个空项用于编辑
    if (!formData.textList.length) {
        formData.textList = ['']
    } else {
        // 如果有数据，添加一个空项方便继续添加
        formData.textList.push('')
    }
    
    if (!formData.imageList.length) {
        formData.imageList = ['']
    } else {
        // 如果有数据，添加一个空项方便继续添加
        formData.imageList.push('')
    }
}

const getDetail = async (row: Record<string, any>) => {
    console.log('获取详情，传入参数:', row)
    const data = await sectionsGetContent({
        id: row.id
    })
    console.log('获取到的数据:', data)
    setFormData(data)
    console.log('设置后的formData:', { ...formData })
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
